/*
 * Copyright © 2022-now 尛飛俠（Denvie） All rights reserved.
 */

package cn.denvie.springcloud.user.controller;

import cn.denvie.springcloud.user.domain.dto.UserDTO;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * UserController。
 *
 * @author Denvie
 * @date 2022/3/29
 * @since 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private RestTemplate restTemplate;

    @SentinelResource(value = "findUserInfoById")
    @GetMapping("/{id}")
    public UserDTO query(@PathVariable Long id) {
        UserDTO userDTO = new UserDTO();
        userDTO.setId(id);
        userDTO.setUsername("user" + id);
        userDTO.setNickname("昵称" + id);
        userDTO.setBalance(BigDecimal.valueOf(ThreadLocalRandom.current().nextInt()));
        if (id % 2 == 0) {
            throw new RuntimeException("模拟运行时错误");
        }
        return userDTO;
    }

    @SentinelResource(value = "listAllUsers")
    @GetMapping("/list")
    public List<UserDTO> list() throws InterruptedException {
        List<UserDTO> userDTOList = new ArrayList<>();
        UserDTO userDTO;
        for (int i = 1; i <= 5; i++) {
            userDTO = new UserDTO();
            userDTO.setId((long) i);
            userDTO.setUsername("user" + i);
            userDTO.setNickname("昵称" + i);
            userDTO.setBalance(BigDecimal.valueOf(ThreadLocalRandom.current().nextInt()));
            userDTOList.add(userDTO);
            TimeUnit.MILLISECONDS.sleep(ThreadLocalRandom.current().nextInt(50));
        }
        return userDTOList;
    }

    @GetMapping("/{userId}/allOrders")
    public List<?> allOrders(@PathVariable Long userId) {
        // 从订单中心查询所有订单
        String url = String.format("http://order-center/order/listAll/%d", userId);
        return restTemplate.getForObject(url, List.class);
    }
}
